#include "actor_server.h"
#include "byte_buffer.h"
#include "actor_packet.h"
#include "TcpConnection.h"
#include "packet.h"
#include <iostream>


as::md::ActorServer::ActorServer(as::net::EpollWatch *ep, as::net::Address &serverAddr, const char *name, int pri_key /*= 0*/)
	:TcpServer(ep, serverAddr, name), pri_key_(pri_key)
{
	this->SetMsgCb(std::bind(&ActorServer::HandleMsg, this, 
		std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
}

as::md::ActorServer::~ActorServer()
{
	
}

void as::md::ActorServer::HandleMsg(as::net::TcpConnectionPtr &conn, ByteBufferPtr &buf, int size)
{
	auto packetPtr = as::md::Packet::PacketData(buf);
	if (packetPtr == nullptr)
		return;

	uint32 sysId = packetPtr->sysId_;
	uint32 subId = packetPtr->subId_;
	auto body = packetPtr->body_;

	//std::cout << "actor server handle msg, sysId:" << sysId << " subId:" << subId << std::endl;
	if (sysId == SYS_MSG)
	{
		if (subId == ReqFrameId)
		{
			int frameId = 0;
			body->read_int32(frameId);
			if (frameId != 0)
			{
				ActorPacket respond(SYS_MSG, RespFrameId);
				respond.write_int32(pri_key_);
				uint8 *b = respond.flust();
				int r = respond.GetSize();
				conn->SendMsg((const char*)b, r);
				conn_map_[frameId] = conn;
			}
		}
		else if (subId == HeartBeat)
		{
			std::cout << "heart beat:" << conn->GetConnId() << std::endl;
		}
		else if(subId == ActorMsg)
		{
			if (actor_msg_fun_)
			{
				actor_msg_fun_(body, body->GetWritePos());
			}
		}
	}
}

void as::md::ActorServer::SetActorMsgCb(ActorMsgCallback fun)
{
	actor_msg_fun_ = fun;
}
